/// [Highly divisible triangular number](https://projecteuler.net/problem=12)
fn main() {
    for length in &[5, 500] {
        let num = highly_divisible_triangular_number(*length);
        println!("The first triangle number to have over {} divisors is {}", length, num);
    }
}
// n * (n+1) / 2
fn highly_divisible_triangular_number(length: u32) -> u32 {
    let mut num = 2;
    let mut count = triangle_numbers_count(num * (num + 1) / 2);
    while count < length {
        num += 1;
        count = triangle_numbers_count(num * (num + 1) / 2);
    }
    num * (num + 1) / 2
}

fn triangle_numbers_count(num: u32) -> u32 {
    if num < 2 {
        0
    } else {
        let mut count = 1;
        let mut x: u32 = 2;
        while x.pow(2) < num {
            if num % x == 0 {
                count += 2;
            }
            x += 1;
        }
        if x.pow(2) == num {
            count + 1
        } else {
            count
        }
    }
}
